<template>
  <div class="annual-summary">
    <div class="header">
      <h3>年度工作总结</h3>
      <div class="controls">
        <el-select v-model="selectedYear" placeholder="选择年份" @change="fetchAnnualData">
          <el-option v-for="year in years" :key="year" :label="year" :value="year" />
        </el-select>
        <el-button type="primary" @click="generateAnnualReport" :loading="generating">
          生成年度报告
        </el-button>
        <el-button type="success" @click="showAISummaryDialog = true">
          <el-icon><MagicStick /></el-icon> AI 年度总结
        </el-button>
      </div>
    </div>

    <!-- 年度统计概览 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon annual">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryStats.annualPlans || 0 }}</div>
              <div class="stat-label">年度计划</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon monthly">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryStats.monthlyPlans || 0 }}</div>
              <div class="stat-label">月度计划</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon weekly">
              <el-icon><List /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryStats.weeklyPlans || 0 }}</div>
              <div class="stat-label">周计划</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon reports">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ summaryStats.weeklyReports || 0 }}</div>
              <div class="stat-label">周报</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 完成率图表 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span>计划完成率</span>
          </template>
          <div class="chart-container">
            <div class="completion-chart">
              <div class="chart-item" v-for="item in completionData" :key="item.type">
                <div class="chart-label">{{ item.label }}</div>
                <div class="chart-bar">
                  <div 
                    class="chart-fill" 
                    :style="{ width: item.percentage + '%', backgroundColor: item.color }"
                  ></div>
                </div>
                <div class="chart-percentage">{{ item.percentage }}%</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <span>状态分布</span>
          </template>
          <div class="chart-container">
            <div class="status-chart">
              <div class="status-item" v-for="item in statusData" :key="item.status">
                <div class="status-indicator" :style="{ backgroundColor: item.color }"></div>
                <div class="status-label">{{ item.label }}</div>
                <div class="status-count">{{ item.count }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 月度趋势 -->
    <el-card class="monthly-trend">
      <template #header>
        <span>月度工作趋势</span>
      </template>
      <div class="trend-container">
        <div class="trend-chart">
          <div 
            v-for="(month, index) in monthlyTrend" 
            :key="index"
            class="trend-bar"
            :style="{ height: month.height + 'px' }"
            :title="`${month.label}: ${month.value}个计划`"
          >
            <div class="trend-value">{{ month.value }}</div>
          </div>
        </div>
        <div class="trend-labels">
          <div v-for="month in monthlyTrend" :key="month.label" class="trend-label">
            {{ month.label }}
          </div>
        </div>
      </div>
    </el-card>

    <!-- 年度报告 -->
    <el-card v-if="annualReport" class="annual-report">
      <template #header>
        <span>{{ selectedYear }}年度工作总结报告</span>
        <el-button type="primary" text @click="downloadReport">下载报告</el-button>
      </template>
      
      <div class="report-content">
        <div class="report-section">
          <h4>年度总结</h4>
          <p>{{ annualReport.summary }}</p>
        </div>
        
        <div class="report-section">
          <h4>主要成就</h4>
          <div class="achievements">
            <p>{{ annualReport.achievements }}</p>
          </div>
        </div>
        
        <div class="report-section">
          <h4>挑战与改进</h4>
          <div class="challenges">
            <p>{{ annualReport.challenges }}</p>
          </div>
        </div>

        <div class="report-section">
          <h4>工作亮点</h4>
          <div class="highlights">
            <p style="white-space: pre-wrap;">{{ annualReport.highlights }}</p>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, Document, List, ChatDotRound, MagicStick } from '@element-plus/icons-vue'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'

export default {
  name: 'AnnualSummary',
  components: {
    Calendar,
    Document,
    List,
    ChatDotRound,
    MagicStick
  },
  setup() {
    const authStore = useAuthStore()
    const years = ref([2023, 2024, 2025, 2026])
    const selectedYear = ref(new Date().getFullYear())
    const loading = ref(false)
    const generating = ref(false)
    const showAISummaryDialog = ref(false)
    const annualReport = ref(null)
    const summaryData = ref({
      annualPlans: [],
      monthlyPlans: [],
      weeklyPlans: [],
      weeklyReports: []
    })

    const summaryStats = computed(() => {
      return {
        annualPlans: summaryData.value.annualPlans?.length || 0,
        monthlyPlans: summaryData.value.monthlyPlans?.length || 0,
        weeklyPlans: summaryData.value.weeklyPlans?.length || 0,
        weeklyReports: summaryData.value.weeklyReports?.length || 0
      }
    })

    const completionData = computed(() => {
      const annualCompleted = summaryData.value.annualPlans?.filter(p => p.status === 'completed').length || 0
      const annualTotal = summaryData.value.annualPlans?.length || 1
      
      const monthlyCompleted = summaryData.value.monthlyPlans?.filter(p => p.status === 'completed').length || 0
      const monthlyTotal = summaryData.value.monthlyPlans?.length || 1
      
      const weeklyCompleted = summaryData.value.weeklyPlans?.filter(p => p.status === 'completed').length || 0
      const weeklyTotal = summaryData.value.weeklyPlans?.length || 1

      return [
        { type: 'annual', label: '年度计划', percentage: Math.round((annualCompleted / annualTotal) * 100), color: '#409eff' },
        { type: 'monthly', label: '月度计划', percentage: Math.round((monthlyCompleted / monthlyTotal) * 100), color: '#67c23a' },
        { type: 'weekly', label: '周计划', percentage: Math.round((weeklyCompleted / weeklyTotal) * 100), color: '#e6a23c' }
      ]
    })

    const statusData = computed(() => {
      const allPlans = [
        ...(summaryData.value.annualPlans || []),
        ...(summaryData.value.monthlyPlans || []),
        ...(summaryData.value.weeklyPlans || [])
      ]
      
      const statusCount = {
        completed: allPlans.filter(p => p.status === 'completed').length,
        in_progress: allPlans.filter(p => p.status === 'in_progress').length,
        pending: allPlans.filter(p => p.status === 'pending').length
      }

      return [
        { status: 'completed', label: '已完成', count: statusCount.completed, color: '#67c23a' },
        { status: 'in_progress', label: '进行中', count: statusCount.in_progress, color: '#e6a23c' },
        { status: 'pending', label: '未开始', count: statusCount.pending, color: '#909399' }
      ]
    })

    const monthlyTrend = computed(() => {
      const months = Array.from({ length: 12 }, (_, i) => i + 1)
      return months.map(month => {
        const count = summaryData.value.monthlyPlans?.filter(p => p.month === month).length || 0
        // Scale height for visualization (max 150px)
        const height = Math.min(count * 20 + 20, 150)
        return {
          label: `${month}月`,
          value: count,
          height
        }
      })
    })

    const fetchAnnualData = async () => {
      loading.value = true
      try {
        // Fetch plans and reports
        const [annualPlansRes, monthlyPlansRes, weeklyPlansRes, weeklyReportsRes, annualReportRes] = await Promise.all([
          axios.get('/api/plans/annual', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get('/api/plans/monthly', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get('/api/plans/weekly', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get('/api/reports/weekly', { headers: { Authorization: `Bearer ${authStore.token}` } }),
          axios.get(`/api/reports/annual?year=${selectedYear.value}`, { headers: { Authorization: `Bearer ${authStore.token}` } })
        ])

        // Filter by selected year
        const year = selectedYear.value
        summaryData.value = {
          annualPlans: annualPlansRes.data.filter(p => p.year === year),
          monthlyPlans: monthlyPlansRes.data.filter(p => p.year === year),
          weeklyPlans: weeklyPlansRes.data.filter(p => p.year === year),
          weeklyReports: weeklyReportsRes.data.filter(p => p.year === year)
        }
        
        annualReport.value = annualReportRes.data
        
      } catch (error) {
        console.error('获取数据失败', error)
        ElMessage.error('获取数据失败')
      } finally {
        loading.value = false
      }
    }

    const generateAnnualReport = async () => {
      generating.value = true
      try {
        const response = await axios.post('/api/reports/annual/generate', {
          year: selectedYear.value
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        annualReport.value = response.data
        ElMessage.success('年度报告生成成功')
      } catch (error) {
        if (error.response && error.response.status === 400) {
             ElMessage.warning('数据不足，无法生成年度报告')
        } else {
             ElMessage.error('生成年度报告失败')
        }
      } finally {
        generating.value = false
      }
    }

    const downloadReport = () => {
      ElMessage.info('下载功能开发中')
    }

    onMounted(() => {
      fetchAnnualData()
    })

    return {
      years,
      selectedYear,
      loading,
      generating,
      showAISummaryDialog,
      annualReport,
      summaryStats,
      completionData,
      statusData,
      monthlyTrend,
      fetchAnnualData,
      generateAnnualReport,
      downloadReport
    }
  }
}
</script>

<style scoped>
.annual-summary {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  color: #333;
}

.controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.annual { background-color: #409eff; }
.stat-icon.monthly { background-color: #67c23a; }
.stat-icon.weekly { background-color: #e6a23c; }
.stat-icon.reports { background-color: #f56c6c; }

.stat-icon .el-icon {
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.charts-row {
  margin-bottom: 20px;
}

.chart-container {
  padding: 20px;
}

.completion-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.chart-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-label {
  width: 80px;
  font-size: 14px;
  color: #666;
}

.chart-bar {
  flex: 1;
  height: 20px;
  background-color: #f0f2f5;
  border-radius: 10px;
  overflow: hidden;
}

.chart-fill {
  height: 100%;
  border-radius: 10px;
  transition: width 0.5s ease;
}

.chart-percentage {
  width: 50px;
  text-align: right;
  font-size: 14px;
  color: #666;
}

.status-chart {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-label {
  flex: 1;
  font-size: 14px;
  color: #666;
}

.status-count {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.monthly-trend {
  margin-bottom: 20px;
}

.trend-container {
  padding: 20px;
}

.trend-chart {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  height: 200px;
  margin-bottom: 10px;
}

.trend-bar {
  flex: 1;
  background: linear-gradient(to top, #409eff, #67c23a);
  border-radius: 4px 4px 0 0;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 5px;
  min-height: 30px;
  transition: height 0.3s ease;
  position: relative;
}

.trend-value {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.trend-labels {
  display: flex;
  gap: 8px;
}

.trend-label {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
}

.report-content {
  padding: 10px;
}

.report-section {
  margin-bottom: 20px;
}

.report-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.report-section p {
  line-height: 1.6;
  color: #666;
  margin: 0;
}

.achievements, .challenges, .highlights {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #67c23a;
}
</style>
